
import 'package:reabampos/src/reabam/operation/db/models.dart';
import 'package:reabampos/src/reabam/operation/rb_api.dart';
import 'package:reabampos/src/reabam/operation/rb_config.dart';
import 'package:reabampos/src/reabam/ui/support/support_get_good_items.dart';
import 'package:reabampos/src/reabam/utils/brean/c_bean_good_item.dart';
import 'package:xsdk_flutter/xsdk/xsdk_flutter_package.dart';

// 业务相关的一些常用方法
abstract class RBBusinessUtils {


  //获得挂单流水号
  static int getSerNo(){
    String today=XDateUtils.getCurrentTime_String(format: XDateUtils.formatTimeDefault3);
    String noteDay=XSharePreferencesUtils.getString("XPendingOrderDate${XSharePreferencesUtils.getString(RBConfigs.SP_companyId)}");
    int SerNo=1;
    if(XStringUtils.isEmpty(noteDay)){
      XSharePreferencesUtils.saveString("XPendingOrderDate${XSharePreferencesUtils.getString(RBConfigs.SP_companyId)}",today);
    }else{
      if (today==noteDay){
        int noteInex=XSharePreferencesUtils.getInt("XPendingOrderSerNo${XSharePreferencesUtils.getString(RBConfigs.SP_companyId)}");
        SerNo=noteInex+1;
      }else{
        XSharePreferencesUtils.saveString("XPendingOrderDate${XSharePreferencesUtils.getString(RBConfigs.SP_companyId)}",today);
      }
    }

    XSharePreferencesUtils.saveInt("XPendingOrderSerNo${XSharePreferencesUtils.getString(RBConfigs.SP_companyId)}",SerNo);
    return SerNo;
  }


  static ComponentBeanGoodItem dbSpecBeanToComponentBean(BeanShoppingCartDBGoodSpec bean) {
    ComponentBeanGoodItem item = ComponentBeanGoodItem.fromJson(bean.toJson());
    // item.jsonData = XJsonUtils.json2Map(bean.jsonData);

    //单位
    if (!XStringUtils.isEmpty(bean.unitListJson)) {
      List<dynamic> unitList = XJsonUtils.json2List(bean.unitListJson);
      if (unitList.length != 0) {
        item.unitList = [];
        for (dynamic u in unitList) {
          item.unitList!.add(ComponentBeanUnit.fromJson(u));
        }
      }
    }

    //唯一码
    if (!XStringUtils.isEmpty(bean.uniqueCodeListJson)) {
      List<dynamic> uniqueCodeList = XJsonUtils.json2List(bean.uniqueCodeListJson);
      if (uniqueCodeList.length != 0) {
        item.currentUniqueCodeList = [];
        for (dynamic u in uniqueCodeList) {
          item.currentUniqueCodeList!.add(ComponentBeanUniqueCode.fromJson(u));
        }
      }
    }
    //批次码
    if (!XStringUtils.isEmpty(bean.batchCodeListJson)) {
      List<dynamic> batchCodeList = XJsonUtils.json2List(bean.batchCodeListJson);
      if (batchCodeList.length != 0) {
        item.currentBatchCodeList = [];
        for (dynamic u in batchCodeList) {
          item.currentBatchCodeList!.add(ComponentBeanBatchCode.fromJson(u));
        }
      }
    }

    //店内加工单
    if (!XStringUtils.isEmpty(bean.adjustTypeListJson)) {
      List<dynamic> adjustTypeList = XJsonUtils.json2List(bean.adjustTypeListJson);
      if (adjustTypeList.length != 0) {
        item.adjustTypeList = [];
        for (dynamic u in adjustTypeList) {
          item.adjustTypeList!.add(u);
        }
      }
    }

    return item;
  }

  static ComponentBeanGoodItem dbBeanToComponentBean(BeanShoppingCartDBGood bean) {
    ComponentBeanGoodItem item = ComponentBeanGoodItem.fromJson(bean.toJson());
    // item.jsonData = XJsonUtils.json2Map(bean.jsonData);
    //单位
    if (!XStringUtils.isEmpty(bean.unitListJson)) {
      List<dynamic> unitList = XJsonUtils.json2List(bean.unitListJson);
      if (unitList.length != 0) {
        item.unitList = [];
        for (dynamic u in unitList) {
          item.unitList!.add(ComponentBeanUnit.fromJson(u));
        }
      }
    }

    //唯一码
    if (!XStringUtils.isEmpty(bean.uniqueCodeListJson)) {
      List<dynamic> uniqueCodeList = XJsonUtils.json2List(bean.uniqueCodeListJson);
      if (uniqueCodeList.length != 0) {
        item.currentUniqueCodeList = [];
        for (dynamic u in uniqueCodeList) {
          item.currentUniqueCodeList!.add(ComponentBeanUniqueCode.fromJson(u));
        }
      }
    }
    //批次码
    if (!XStringUtils.isEmpty(bean.batchCodeListJson)) {
      List<dynamic> batchCodeList = XJsonUtils.json2List(bean.batchCodeListJson);
      if (batchCodeList.length != 0) {
        item.currentBatchCodeList = [];
        for (dynamic u in batchCodeList) {
          item.currentBatchCodeList!.add(ComponentBeanBatchCode.fromJson(u));
        }
      }
    }

    //店内加工单
    if (!XStringUtils.isEmpty(bean.adjustTypeListJson)) {
      List<dynamic> adjustTypeList = XJsonUtils.json2List(bean.adjustTypeListJson);
      if (adjustTypeList.length != 0) {
        item.adjustTypeList = [];
        for (dynamic u in adjustTypeList) {
          item.adjustTypeList!.add(u);
        }
      }
    }

    return item;
  }


  //vo转dao
  static BeanShoppingCartDBGood componentBeanToDBBean(
      {required ComponentBeanGoodItem bean, required String xTag, double? quantity}) {
    if (quantity != null) {
      bean.currentQuantity = quantity;
    }

    BeanShoppingCartDBGood dbItem = BeanShoppingCartDBGood.fromJson(bean.toJson());
    dbItem.xTag = xTag;

    return dbItem;
  }

  static BeanShoppingCartDBGoodSpec componentBeanToDBBeanSpec(
      {required ComponentBeanGoodItem bean, required String xTag, double? quantity}) {
    if (quantity != null) {
      bean.currentQuantity = quantity;
    }
    BeanShoppingCartDBGoodSpec dbItem = BeanShoppingCartDBGoodSpec.fromJson(bean.toJson());
    dbItem.xTag = xTag;
    return dbItem;
  }


  //是否多规格
  static bool isSpecType(dynamic item_specType) {
    if (item_specType is ComponentBeanGoodItem) {
      ComponentBeanGoodItem item = item_specType;
      return item.specType != null && '${item.specType}' != '0';
    }

    return item_specType != null && '$item_specType' != '0';
  }


  //自助收银/////////////////////////////////////////////////////////////////////

  //搜索商品
  static void scanFindGood_and_addToShoppingcart_selfService(XPageState statePage,String sword){
    //test...
    //sword='40630128';

    Map<String,dynamic> requestMap={};
    requestMap['pageIndex']=1;
    requestMap['pageSize']=20;
    requestMap['sword']=sword;

    SupportGetGoodItems.searchGoodItems(
        statePage,
        requestMap,
        isSearchMainItem:false,
        callback:(Map<String,dynamic> result) {

          List<Map<String, dynamic>> items=result['items']??[];
          int size=items.length;
          //XLogUtils.printLog('---搜索数据库结果items,size=$size');
          if(size!=1){
            statePage.toast('条码对应多个商品，请联系店员');
            return;
          }
          //XLogUtils.printLog('---items[0]=${XJsonUtils.obj2Json(items[0])}',isPrintAll: true);
          //XFileUtils.writeToFile('${XTempData.appDocumentsDirectoryPath}/findItemJson.txt', XJsonUtils.obj2Json(items[0]));

          //添加到购物车
          ComponentBeanGoodItem item =ComponentBeanGoodItem.fromJson(items[0]);
          item.id='${XDateUtils.getCurrentTime_ms()}${XNumberUtils.randomInt(100)+900}';
          item.staff=XJsonUtils.json2Map(XSharePreferencesUtils.getString(RBConfigs.SP_staff));
          item.currentPrice=item.dealPrice??0;
          item.currentQuantity=1;
          item.currentMoney=XNumberUtils.mul(item.currentQuantity, item.currentPrice);
          //
          addToShoppingCart_selfService(item);
          //通知更新购物车
          XNotifyStateChangeUtils.notifyStateChange(
              action: RBConfigs.NotifyAction_selfService_update_shoppingcart,
              key: 'key',
              value: 'value'
          );
        }
    );
  }


  //static String? fastOrderNo;
  static String? memberId;
  static List<ComponentBeanGoodItem> list_shoppingcart_selfService=[];
  static Map<String,dynamic> shoppingcartInfo_selfService={};
  //添加商品
  static void addToShoppingCart_selfService(ComponentBeanGoodItem item){
    list_shoppingcart_selfService.insert(0, item);
    //计算
    updateShoppingCartInfo_selfService();
  }

  //更新购物车信息
  static void updateShoppingCartInfo_selfService(){
    double totalQuantity=0;
    double totalMoney=0;
    for(ComponentBeanGoodItem item in list_shoppingcart_selfService){
      item.currentMoney=XNumberUtils.mul(item.currentQuantity, item.currentPrice??item.dealPrice??0);
      totalQuantity=XNumberUtils.add(totalQuantity, item.currentQuantity);
      totalMoney=XNumberUtils.add(totalMoney, item.currentMoney);
    }
    //
    shoppingcartInfo_selfService['totalCount']=list_shoppingcart_selfService.length;
    shoppingcartInfo_selfService['totalQuantity']=totalQuantity;
    shoppingcartInfo_selfService['totalMoney']=totalMoney;
  }


  //自助收银反扫支付
  static void pay_selfService(XPageState statePage,String sword){

    List<dynamic> items=[];
    for(ComponentBeanGoodItem iitem in RBBusinessUtils.list_shoppingcart_selfService){
      Map<String,dynamic> item={};
      item['id']=iitem.id;
      item['itemId']=iitem.itemId;
      item['specId']=iitem.specId;
      item['itemName']=iitem.itemName;
      item['specName']=iitem.specName;
      item['itemCode']=iitem.itemCode;
      item['skuBarcode']=iitem.skuBarcode;
      item['quantity']=iitem.currentQuantity;
      item['itemQuantity']=iitem.currentQuantity;
      item['dealPrice']=iitem.dealPrice;
      //item['totalPaidAmount']=iitem.; //已付金额
      item['totalRealPrice']=iitem.currentMoney;
      //
      items.add(item);
    }

    //生成orderId
    int machineCode=XSharePreferencesUtils.getInt(RBConfigs.SP_MachineCode);
    String companyCode=XSharePreferencesUtils.getString(RBConfigs.SP_CompanyCode);
    String orderId='$companyCode$machineCode${XDateUtils.getCurrentTime_ms()}${XNumberUtils.randomInt(100)+100}';

    statePage.showLoading(isOurSideCanClick: false);

    //开始
    XNotifyStateChangeUtils.notifyStateChange(
        action: RBConfigs.NotifyAction_selfService_pay_check,
        key: 'start',
        value: ''
    );

    RBBaseApi.pay_ss(
        payType: RBConfigs.payParentType,
        payTypeName: RBConfigs.payParentTypeName,
        orderId: orderId,
        memberId: RBBusinessUtils.memberId,
        items: items,
        payAmount: RBBusinessUtils.shoppingcartInfo_selfService['totalMoney'],
        scanCode: sword,
        succeed: (response, Map<String, dynamic> responseMap, Map<String, dynamic> headers_response) {
          statePage.hideLoading();

          String? gatheringId=responseMap['data']?['gatheringId'];
          XLogUtils.printLog('---gatheringId=$gatheringId');

          //通知更新购物车
          XNotifyStateChangeUtils.notifyStateChange(
              action: RBConfigs.NotifyAction_selfService_pay_check,
              key: orderId,
              value: gatheringId
          );

        },
        failed: (String code, String msg) {
          statePage.hideLoading();
          statePage.toast(msg);

          XNotifyStateChangeUtils.notifyStateChange(
              action: RBConfigs.NotifyAction_selfService_pay_check,
              key: 'failed',
              value: ''
          );

        }
    );

  }


}
